package com.ruoyi.job.task;


import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.job.domain.ElevatorToken;
import com.ruoyi.job.util.Md5Util;
import com.ruoyi.job.util.Signed;
import com.ruoyi.omp.api.RemoteInspectionService;
import com.ruoyi.omp.api.factory.RemoteRoomFactory;
import com.ruoyi.system.api.enums.ElevatorValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;

@Component("elevatorTask")
public class ElevatorTask {

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteInspectionService inspectionService;

    /**
     * 获取梯联网token 7天过期
     */
    public void getElevatorTokenTask(){

        String url = "https://micoliftdt.dataserver.cn/extend/elevator/api!dnss_getToken.do";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        String timeStamp = df.format(new Date());
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("appkey", ElevatorValue.APP_KEY);
        params.put("password", Md5Util.generate32md5(ElevatorValue.PASSWORD));
        params.put("timeStamp", timeStamp);
        params.put("appSecret", ElevatorValue.APP_SECRET);
        params.put("userName", ElevatorValue.USER);
        String sign =  Signed.getSignString(params);
        params.put("sign", sign);
        String request = JSONUtil.toJsonStr(params);
        String resultStr = HttpRequest.post(url).header("content-type","application/json;charset=utf-8").body(request).execute().body();
        ElevatorToken result  = JSON.parseObject(resultStr, ElevatorToken.class);

        if ("0".equals(result.getErrorCode())){
            //存储token到redis
            redisService.setCacheObject("elevator_token", result.getData().getToken());
        }else {
            System.out.println("token 获取异常 ===>" + result.getErrorMsg());
        }

    }

    //获取电梯运行历史数据

    public void getElevatorHistory(Integer offset)
    {
        System.out.println("elevatorTask 执行无参方法");
        R r =null;
        //获取当前日期-1，
        if(offset>0){
            Date date = new Date(System.currentTimeMillis()- offset*1000*60*60* 24);
            SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
            //调用接口生成报表
//        R r = staticsticsService.genStaticByDate(sp.format(date));
            r = inspectionService.syncInfo(sp.format(date));

        }else {
            r = inspectionService.syncInfo(null);
        }
        if(r.getCode() == Constants.SUCCESS){
            System.out.println("获取电梯运行历史数据成功 " );
        }

    }

}



